<template>
	<view class="page-submit-order">
		<page-header title="确认订单" background="#F7F0E6" color="black"></page-header>
		<view class="page-body" v-if="!Data.loadding[0] && !Data.loadding[1]">
			<view class="address" @tap="gotoAddressList">
				<image class="icon" src="../../static/img/location-submit.png"></image>
				<block v-if="userAddr && userAddr.addrId">
					<view class="group">
						<view class="name">{{ userAddr.consignee }}
							<text class="mobile">{{ userAddr.mobile }}
							</text>
						</view>
						<view class="address-name">{{ userAddr.city + userAddr.area + userAddr.addr }}</view>
					</view>
				</block>
				<block v-else>
					<view class="group">
						暂无可用地址，请点击添加
					</view>
				</block>
			</view>
			<view class="item-list">
				<block v-for="(shopItem, shopIndex) in shopCartOrders" :key="shopIndex">
					<block v-for="(item, index) in shopItem.shopCartItemVO" :key="'1' + index">
						<view class="shop-item">
							<image class="background" :src="addDomain('/static/cart-item.png')"></image>
							<view class="content">
								<view class="header">
									<image class="icon" src="/static/images/shop.png" />
									{{ shopItem.shopName }}
									<uni-icons class="right" type="right" color="white"></uni-icons>
								</view>
								<view class="body">
									<image class="left" :src="item.imgUrl" mode="aspectFill"></image>
									<view class="right">
										<view class="text-overflow-clamp-2"> {{ item.spuName }}</view>
										<view class="sku">
											<view class="skuItem">[{{ item.skuName }}]</view>
										</view>
										<view class="price-box">
											<price-point :price="item.skuPriceFee" :point="item.pointPrice"
												:size="30"></price-point>
											<view>x{{ item.count }}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="viewer" v-if="item.needIdCard == 1">
							<view class="header">
								实名观影人
								<view class="tips">仅需选择{{ item.count }}位；入场需携带对应证件</view>
							</view>
							<view class="card">
								<block v-if="Data.orderEntry == 1">
									<view class="card-item" v-for="(cardItem, index) in Data.idCardList" :key="index"
										@tap="selectIdCards(cardItem.id, item.count)">
										<view class="left">
											<view class="name">{{ cardItem.name }}</view>
											<view class="idcard">{{queryType(cardItem.type)}}
												{{ handleIdCard(cardItem.idCard) }}
											</view>
										</view>
										<view class="right">
											<!-- <checkbox class="check" disabled="true" :checked="" /> -->
											<uni-icons type="checkbox" color="#DA9974" :size="24"
												v-if="Data.selectIdCard.includes(cardItem.id)"></uni-icons>
											<uni-icons type="circle" color="#DA9974" :size="24" v-else></uni-icons>
										</view>
									</view>
									<view class="button" @tap="toViewer">
										<uni-icons type="personadd" color="#b8543e"></uni-icons>
										添加观影人
									</view>
								</block>
								<block v-else>
									<view class="card-item" v-for="(cardItem, index) in handleIdCards(item.idCards)"
										:key="index">
										<view>
											<view class="name">{{ queryName(cardItem) }}</view>
											<view class="idcard">{{ queryType(cardItem.split(":")[2]) }}
												{{ handleIdCard(cardItem.split(":")[0]) }}
											</view>
										</view>
									</view>
								</block>
							</view>
						</view>
					</block>
					<!-- 优惠券 -->
				<!-- 	<view v-if="coupon.length >= 1">
					  可用优惠券
					  <view v-for="(item, index) in coupon" :key="index" @click="chooseCoupon(item)">{{item}}
					   <view class="item">
					      <view class="tit">
					        <uni-icons :color="selectedCoupon === item.id ? '#DA9974' : '#ccc'" type="circle" />
					        <view class="text" v-if="selectedCoupon === item.id">
					          优惠券金额：¥{{item.price}}*0.01
					        </view>
					        <view class="text" v-else>
					          未选优惠券：{{item.name}}
					        </view>
					      </view>
					    </view>
					  </view>
					</view> -->
					<view class="order-info">
						<view class="post-item">
							<view class="item-box">
                <view class="item">
                	<view class="tit" style="display: flex; align-items: center;">
                     <image src="../../static/img/redbag.png" />
                		优惠券：
                	</view>
                	<view class="text"  >
                    <view class="text" v-if="coupon.length >= 1">
                    <view v-for="(item, index) in coupon" :key="index" @click="chooseCoupon(item)" style='display: flex;'>
                      <uni-icons :color="selectedCoupon === item.id ? '#fff' : '#ccc'" :type="selectedCoupon === item.id ? 'checkbox' : 'circle'" />
                             <view class="text2" v-if="selectedCoupon === item.id">
                             -  ¥{{item.price*0.01}}
                             </view>
                             <view class="text1" v-else>
                               未选优惠券：{{item.name}}
                             </view>
                    </view>

                    </view>
                    <view class="text"  v-else>
                      暂无可用的优惠券
                      </view>
                	</view>

                </view>
								<view class="item">
									<view class="tit">
										订单金额：
									</view>
									<view class="text">
										<price-point :price="total" :point="totalPointPrice" :size="36"></price-point>
									</view>
								</view>
								<view class="item">
									<view class="tit">
										配送方式：
									</view>
									<view class="text" style="display: flex;">
										<view style="display: flex;" @tap="selectDvyType(3)">
											<uni-icons color="#DA9974" type="checkbox" size="20"
												v-if="Data.dvyType == 3"></uni-icons>
											<uni-icons color="#DA9974" type="circle" size="20" v-else></uni-icons>无需配送
										</view>
										<view style="display: flex;" @tap="selectDvyType(2)">
											<uni-icons color="#DA9974" type="checkbox" size="20"
												v-if="Data.dvyType == 2"></uni-icons>
											<uni-icons color="#DA9974" type="circle" size="20" v-else></uni-icons>顺丰快递
										</view>
									</view>
								</view>
								<view class="item" v-if="Data.dvyType == 2">
									<view class="tit">
										快递费用：
									</view>
									<view class="text">
										<price-point :price="Data.dvyPrice" :size="30"></price-point>
									</view>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
		</view>
		<view class="bottom-box" v-if="!Data.loadding[0] && !Data.loadding[1]">
			合计：
			<view class="price-total">
				<price-point :price="total + Data.dvyPrice" :point="totalPointPrice" :size="36"></price-point>
			</view>
			<view class="rgb-button" @tap="submitOrder">
				提交订单
			</view>
		</view>
	</view>
</template>

<script setup>
	const Data = reactive({
		isFirst: true,
		total: 0,
		totalCount: 0,
		totalPointPrice: 0,
		shopCartOrders: [],
		// 地址相关
		// orderEntry 1为立即购买,否则为从购物车提交
		orderEntry: '',
		idCardList: [],
		selectIdCard: [],
		selectIdCount: 0,
		needIdCard: 0,
		// 当前订单选择的地址id
		addrId: 0,
		// 当前订单选择的用户地址
		userAddr: {},
		consignee: '',
		mobile: '',
		addr: '',
		provinceId: 0,
		cityId: 0,
		areaId: 0,
		province: '',
		city: '',
		area: '',
		// 订单类型
		orderType: '',
		// dvyType 3=无需快递线下自提 2=顺丰快递。
		dvyType: 3,
		dvyPrice: 0,
		loadding: [true, true],
		coupon: [],
		chooseCouponId: null
	})
	const {
		total,
		totalCount,
		totalPointPrice,
		shopCartOrders,
		idCardList,
		selectIdCard,
		orderEntry,
		selectIdCount,
		needIdCard,
		addrId,
		userAddr,
		consignee,
		mobile,
		addr,
		province,
		city,
		area,
		dvyType,
		dvyPrice,
		loadding,
		coupon
	} = toRefs(Data)

const selectedCoupon = ref(null);
const isCouponChosen = ref(false);
	onLoad((options) => {
		console.log(options);
		if (options.orderEntry) {
			Data.orderEntry = options.orderEntry
		}
		if (options.addrId) {
			Data.addrId = parseInt(options.addrId)
		}
		if (options.dvyType) {
			Data.dvyType = parseInt(options.dvyType)
		}
	})

	onShow(() => {
		uni.getStorage({
			key: 'cloudAddress'
		}).then(res => {
			if (res.data != '' && !Data.isFirst) {
				Data.addrId = res.data
				console.log(Data.addrId);
			}
			loadOrder(Data.isFirst)
		}).catch(res => {
			Data.addrId = 0
			loadOrder(Data.isFirst)
		})
		// 加载订单数据
		getIdCardList()
	})
	// 获取可用优惠券
	const getCoupon = () => {
		if (Data.orderEntry === '1') {
			let spuId = JSON.parse(uni.getStorageSync('cloudShopCartItem')).spuId
			http.request({
				url: '/mall4cloud_point/app/coupon/getCouponUserBySpuId?spuId=' + spuId
			}).then((res) => {
				Data.coupon = res
			})
		} else {
			Data.coupon = []
			Data.shopCartOrders.forEach((shopCartOrder)=>{
				shopCartOrder.shopCartItemVO.forEach((shopCartItem)=>{
					http.request({
						url: '/mall4cloud_point/app/coupon/getCouponUserBySpuId?spuId=' + shopCartItem.spuId
					}).then((res) => {
						const mergedArray = [...Data.coupon]; // 先把 Data.coupon 复制到 mergedArray
						const existingIds = new Set(Data.coupon.map(item => item.id)); // 收集 Data.coupon 中所有对象的 id
						
						// 遍历 res，只有当对象的 id 不在 existingIds 中时，才添加到 mergedArray
						res.forEach(item => {
						  if (!existingIds.has(item.id)) {
						    mergedArray.push(item);
						  }
						});
						Data.coupon = mergedArray
					})
					
				})
			})
		}
	}
	// 选择使用优惠券
	const chooseCoupon = (item) =>{
    if (!isCouponChosen.value) { // 如果还没有选择过优惠券
        selectedCoupon.value = item.id; // 选中优惠券
        isCouponChosen.value = true; // 设置标志变量为已选择
        }
		Data.chooseCouponId = item.id
		loadOrder()
	}
	/**
	 * 获取观演人列表
	 */
	const getIdCardList = () => {
		const params = {
			url: '/mall4cloud_user/app/idCard/list',
			method: 'GET'
		}
		http.request(params).then((res) => {
			Data.idCardList = res
			Data.loadding[1] = false
		})
	}

	/**
	 * 加载订单数据
	 */
	const loadOrder = (isFirst) => {
		const params = {
			url: '/mall4cloud_order/a/order/confirm',
			method: 'POST',
			data: {
				addrId: Data.addrId,
				dvyType: Data.dvyType,
				couponId: Data.chooseCouponId,
				shopCartItem: Data.orderEntry === '1' ? JSON.parse(uni.getStorageSync('cloudShopCartItem')) :
					undefined
			}
		}
		http.request(params).then(res => {
			const shopCartOrders = res.shopCartOrders
			const remarksList = []
			shopCartOrders.forEach((shopCart, index) => {
				shopCart.shopCartItemVO.forEach(prodItem => {
					if (prodItem.imgUrl.indexOf('http') === -1) {
						prodItem.imgUrl = import.meta.env.VITE_APP_RESOURCES_URL + prodItem
							.imgUrl
					}
					if (prodItem.needIdCard == 1) Data.needIdCard = 1
				})
				if (isFirst) {
					shopCart.remarks = ''
				} else {
					remarksList.push(shopCart.remarks)
					shopCartOrders[index].remarks = remarksList[index]
				}
			})
			Data.dvyPrice = res.dvyPrice
			Data.shopCartOrders = shopCartOrders
			Data.total = res.total
			Data.totalCount = res.totalCount
			Data.totalPointPrice = res.totalPointPrice
			Data.userAddr = res.userAddr
			if (Data.userAddr) {
				Data.addrId = res.userAddr.addrId
				Data.addrIds = [res.userAddr.provinceId, res.userAddr.cityId, res.userAddr.areaId]
			}
			// 加载可用优惠券
			getCoupon()

			Data.loadding[0] = false
		}).catch(res => {
			if (Data.dvyType == 3) {

			} else {
				Data.dvyType = 3
				loadOrder()
			}
			if (res.msg == '商品不存在') {
				uni.showToast({
					title: '该商品已下架',
					icon: 'none'
				})
			}
		})
		Data.isFirst = false
	}

	/**
	 * 去观演人
	 */
	const toViewer = () => {
		uni.navigateTo({
			url: '/pages/my-viewer/my-viewer'
		})
	}

	/**
	 * 从观演人列表中获取name
	 */
	const queryNameInIdList = (id) => {
		const arr = Data.idCardList.filter(item => item.idCard == id)
		if (arr.length == 0) {
			return '用户未绑定该身份信息'
		}
		return arr[0].name
	}

	//选择身份证
	const selectIdCards = (id, count) => {
		if (Data.selectIdCard.includes(id)) {
			Data.selectIdCard = Data.selectIdCard.filter(item => item != id)
			Data.selectIdCount--
		} else {
			if (Data.selectIdCard.length >= count) {
				uni.showToast({
					title: '所需观演人已选齐',
					icon: 'none'
				})
				return
			} else {
				Data.selectIdCard.push(id)
				Data.selectIdCount++
			}
		}
		let ShopCartItem = JSON.parse(uni.getStorageSync('cloudShopCartItem'))
		ShopCartItem = {
			...ShopCartItem,
			idCards: handleSelectIdCard()
		}
		uni.setStorage({
			key: 'cloudShopCartItem',
			data: JSON.stringify(ShopCartItem),
			success: () => {
				loadOrder()
			}
		})
	}

	const handleSelectIdCard = () => {
		let arr = []
		Data.idCardList.forEach(item => {
			if (Data.selectIdCard.includes(item.id)) {
				arr.push(`${item.idCard}:${item.name}:${item.type}`)
			}
		})
		return arr.join(",")
	}

	//身份证号码脱敏
	const handleIdCard = (id) => {
		return String(id).slice(0, 3) + '********' + String(id).slice(16)
	}

	//处理身份证列表
	const handleIdCards = (arr) => {
		if (arr == "") {
			return []
		}
		return arr.split(',')
	}

	/**
	 * 从观演人列表中获取name
	 */
	const queryName = (item) => {
		return item.split(":")[1]
	}

	/**
	 * 从item获取类型
	 */
	const queryType = (type) => {
		return ['', '身份证', '港澳台居民居住证', '港澳居民来往内地通行证', '台湾居民来往大陆通行证', '护照', '外国人永久居留身份证'][type]
	}

	/**
	 * 提交订单
	 */
	const submitOrder = () => {
		if (Data.userAddr == null && Data.dvyType == 2) {
			uni.showToast({
				title: `请选择收货地址`,
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (Data.orderEntry == 1 && Data.needIdCard == 1 && Data.selectIdCount != Data.totalCount) {
			uni.showToast({
				title: `请选择${Data.totalCount}位观演人`,
				duration: 2000,
				icon: 'none'
			})
			return
		}
		const shopCartOrders = Data.shopCartOrders
		const orderShopParam = []
		shopCartOrders.forEach(shopCart => {
			orderShopParam.push({
				remarks: shopCart.remarks,
				shopId: shopCart.shopId
			})
		})
		const params = {
			url: '/mall4cloud_order/a/order/submit',
			method: 'POST',
			data: {
				orderShopParam
			}
		}
		http.request(params).then((res) => {
			const orderIds = res.join(',')
			uni.redirectTo({
				url: `/pages/payment/payment?orderIds=${orderIds}&dvyType=1`
			})
		})
	}
	const gotoAddressList = () => {
		uni.navigateTo({
			url: '/pages/address-list/address-list?link=true'
		})
	}
	const selectDvyType = (value) => {
		if (Data.userAddr == null && value == 2) {
			uni.showToast({
				title: `请选择收货地址`,
				duration: 2000,
				icon: 'none'
			})
			return
		}
		Data.dvyType = value
		Data.dvyPrice = 0
		loadOrder()
	}
	// 添加图片域名
	const addDomain = (path) => {
		const resourcesUrl = import.meta.env.VITE_APP_FILE_URL
		if (!path || /^http?:\/\//.test(path)) {
			return path
		} else {
			return resourcesUrl + path
		}
	}
</script>

<style></style>

<style lang="scss" scoped>
	@use "submit-order";
</style>
